package com.example.hzit.handler;

import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.cloud.gateway.support.NotFoundException;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

@Order(-1)
@Component
public class GatewayExceptionHandler implements ErrorWebExceptionHandler {

    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        // 获取响应对象
        ServerHttpResponse response = exchange.getResponse();

        // 如果响应已经提交，直接返回错误
        if (response.isCommitted()) {
            return Mono.error(ex);
        }

        // 设置响应状态码
        response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
        response.getHeaders().setContentType(MediaType.TEXT_PLAIN);

        // 根据不同类型的异常设置不同的消息
        String msg;
        if (ex instanceof NotFoundException) {
            response.setStatusCode(HttpStatus.NOT_FOUND);
            msg = "服务未找到";
        } else if (ex instanceof ResponseStatusException) {
            response.setStatusCode(((ResponseStatusException) ex).getStatus());
            msg = ((ResponseStatusException) ex).getReason();
        } else {
            msg = "内部服务器错误";
        }

        // 记录异常日志
        exchange.getLog().error("[网关异常处理]请求路径: {}, 异常信息: {}", exchange.getRequest().getPath(), ex.getMessage());

        // 设置响应体并返回
        byte[] bytes = msg.getBytes(StandardCharsets.UTF_8);
        return response.writeWith(Mono.just(response.bufferFactory().wrap(bytes)));
    }
}
